package com.kinon.ceshiaccount.network;

import android.os.NetworkOnMainThreadException;
import android.util.Log;

import com.google.gson.JsonSyntaxException;
import com.kinon.ceshiaccount.bean.base.BaseBean;
import com.kinon.ceshiaccount.constant.Constant;

import org.json.JSONException;

import java.net.SocketTimeoutException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by luohao on 2017-07-25.
 */

public abstract class MyCallback<T> implements Callback<T> {


    private final String TAG="lh_mycallback";
    private final int SUCCESS_CODE=200;



    @Override
    public void onResponse(Call<T> call, Response<T> response){
        int resCode=response.code();
        BaseBean<T> bean=null;
        if (resCode==SUCCESS_CODE) {
            try {
                bean= (BaseBean<T>) response.body();
//                Log.e(TAG, "data=="+bean.getData());
               //判断请求code是否是true
                if(bean.isCode()==true){
                    onSuccess(call,response);
                }
                else{
                  BaseBean base= (BaseBean) response.body();
                  logOnError(resCode,base.getMsg());
                }
            } catch (Exception e){

//                Log.e(TAG, "exception== "+e.toString() );
//                if(e instanceof JSONException){
//                    logOnError(Constant.ERROR_JSONE,"数据解析异常");
//                }
//                if(e instanceof IllegalAccessException){
//                    logOnError(Constant.ERROR_JSONE,"数据转换异常");
//                }
                logOnError(-2,"数据解析异常");
                e.printStackTrace();
            }


        }
        else if(response.code()== Constant.NETWORK_NO_FIND){ //常见的404错误
            logOnError(resCode,"请求地址找不到");
        }else{
            logOnError(resCode,"网络请求异常");
        }
    }



    @Override
    public void onFailure(Call<T> call, Throwable t){
//        call.request().newBuilder().build().body()
        t.printStackTrace();
        Log.e(TAG, "onFailure=="+t.toString() );
        if(t instanceof SocketTimeoutException) {
            logOnError(Constant.ERROR_TIMEOUT_CODE, "网络请求超时");
        }else if(t instanceof JSONException || t instanceof JsonSyntaxException){
            logOnError(Constant.ERROR_JSONE,"数据异常");
        }else if(t instanceof NetworkOnMainThreadException) {
            logOnError(Constant.ERROR_NETWORK,"网络异常,请检查网络");
        }else{
            logOnError(-3,"获取信息失败");
        }
//        logOnError(-3,"获取信息失败");
    }



    private void logOnError(int code,String error){
        Log.e(TAG,"code=="+code+"--error=="+error);
        onError(code,error);
    }
    public abstract void onSuccess(Call<T> call, Response<T> response);
    public abstract void onError(int code, String error);
}
